<template>
  <a-drawer
      :title="title"
      width="800"
      placement="right"
      :closable="false"
      :visible="visible"
      :after-visible-change="afterVisibleChange"
      @close="onClose">
    <a-spin :spinning="loading">
      <a-form-model ref="dataForm" :model="dataForm" :rules="validatorRules">
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="评估人部门" prop="deptName">
          <select-tree :options="departTree" v-model="appraiserDept" @change="changeDept"></select-tree>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="评估人姓名" prop="appraiserName">
          <select-query :options="userList" v-model="appraiserUser" @change="changeUser"></select-query>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="评估人手机号" prop="appraiserPhone">
          <a-input placeholder="请输入评估人手机号" v-model="dataForm.appraiserPhone" />
        </a-form-model-item>

        <a-table bordered :rowKey="(record, index) => index" :data-source="dataForm.subList" :columns="columns" size="small" :pagination="false">
          <template slot="assessedUser" slot-scope="text, record">
            <editable-cell :text="text" :options="userListDefault" type="users" @change="onCellChange(record.key, 'assessedUser', $event)" />
          </template>
          <template slot="assessedDept" slot-scope="text, record">
            <span>{{ text }}</span>
          </template>
          <template slot="appraiseTie" slot-scope="text, record">
            <editable-cell :text="text" type="ties" @change="onCellChange2(record.key, 'appraiseTies', $event)" />
          </template>
          <template slot="operation" slot-scope="text, record">
            <a-popconfirm
                v-if="dataForm.subList.length"
                title="Sure to delete?"
                @confirm="() => onDelete(record.key)">
              <a href="javascript:;">Delete</a>
            </a-popconfirm>
          </template>
        </a-table>
        <a-form-model-item>
          <a-button type="dashed" style="width: 60%" @click="handleAdd">
            <a-icon type="plus" />
            Add field
          </a-button>
        </a-form-model-item>
      </a-form-model>
      <div class="anty-form-btn">
        <a-button @click="emptyCurrForm" type="default" htmlType="button" icon="sync">重置</a-button>
        <a-button @click="submitCurrForm" type="primary" htmlType="button" icon="form">保存</a-button>
      </div>
    </a-spin>
  </a-drawer>
</template>

<script>
import { queryDepartTreeList, selectUserList } from '@/api/api'
import { isMobile } from '@/utils/validate'
import { httpAction } from '@/api/manage'

const EditableCell = {
  template: `
    <div class="editable-cell">
    <div v-if="editable" class="editable-cell-input-wrapper">
      <select-query v-if="type === 'users'" :options="options" v-model="value" @change="handleChange"></select-query>
      <select-ties v-else-if="type === 'ties'" v-model="value" @change="handleChange"></select-ties>
      <a-icon
          type="check"
          class="editable-cell-icon-check"
          @click="check" />
    </div>
    <div v-else class="editable-cell-text-wrapper">
      {{ value ? value.label : ' ' }}
      <a-icon type="edit" class="editable-cell-icon" @click="edit" />
    </div>
    </div>
  `,
  props: {
    text: Object,
    type: String,
    options: {
      type: Array,
      // required: true,
      default: () => []
    },
  },
  data () {
    return {
      value: this.text,
      editable: false,
      assessedUser: {},
      appraiseTies: {},
    };
  },
  watch: {
    text(value) {
      this.value = value
    },
  },
  methods: {
    handleChange (e) {
      const value = e;
      if (value) {
        for (let i = 0; i < this.options.length; i++) {
          if (this.options[i].id === e.key) {
            value.deptName = this.options[i].deptName
            break;
          }
        }
      }
      console.log('value', value)
      this.value = value;
    },
    check () {
      this.editable = false;
      this.$emit('change', this.value);
    },
    edit () {
      this.editable = true;
    },
  },
};
export default {
  name: "relations-form",
  components: {
    EditableCell,
  },
  data () {
    return {
      title: '',
      visible: false,
      loading: false,
      appraiserDept: {},
      appraiserUser: {},
      assessedUser: {},
      appraiseTies: {},
      dataForm: {
        id: '',
        deptId: '',
        deptName: '',
        appraiserId: '',
        appraiserName: '',
        appraiserPhone: '',
        questionId: '',
        subList: [
          // { assessedUser: '', assessedDept: '', appraiseTies: '', }
        ]
      },
      dataFormDefault: {},
      departTree: [],
      userList: [],
      userListDefault: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      columns: [
        {
          // todo 编辑评估关系
          title: '被评估人',
          dataIndex: 'assessedUser',
          scopedSlots: { customRender: 'assessedUser' },
        },
        {
          title: '被评估人部门',
          dataIndex: 'assessedDept',
          scopedSlots: { customRender: 'assessedDept' },
        },
        {
          title: '评估人与被评估人关系',
          dataIndex: 'appraiseTie',
          scopedSlots: { customRender: 'appraiseTie' },
        },
        {
          title: 'operation',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      url: {
        save: '/appraise/insertAppraise',
        edit: '/appraise/updateAppraise',
      }
    }
  },
  computed: {
    validatorRules () {
      var validateMobile = (rule, value, callback) => {
        if (value && !isMobile(value)) {
          return callback("您的手机号码格式不正确!")
        }
        callback()
      }
      return {
        appraiserName: [
          { required: true, message: '请输入评估人姓名!', trigger: 'change' }
        ],
        appraiserPhone: [
          { required: true, message: '请输入评估人手机号!', trigger: 'blur' },
          { validator: validateMobile }
        ],
      }
    },
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate(['appraiserName', 'appraiserPhone'])
        // this.$refs['dataForm'].resetFields()
        this.loading = true
        Promise.all([
          this.getInfo(),
          this.loadDeptTree(),
          this.loadUserList(),
          this.loadUserList2()
        ]).then(() => {
          console.log('this.dataForm', this.dataForm)
          this.loading = false
        })
      })
    },
    getInfo() {
      return new Promise((resolve, reject) => {
        this.appraiserDept = { value: this.dataForm.deptId, label: this.dataForm.deptName }
        this.appraiserUser = { key: this.dataForm.appraiserId, label: this.dataForm.appraiserName }
        for (let i = 0; i < this.dataForm.subList.length; i++) {
          this.dataForm.subList[i].key = i
          this.dataForm.subList[i].assessedUser = {
            key: this.dataForm.subList[i].assessedId,
            label: this.dataForm.subList[i].assessedName
          }
          this.dataForm.subList[i].appraiseTie = {
            key: this.dataForm.subList[i].appraiseTiesId,
            label: this.dataForm.subList[i].appraiseTies
          }
        }
        this.dataFormDefault = JSON.parse(JSON.stringify(this.dataForm))
        resolve()
      })
    },
    loadDeptTree () {
      return new Promise((resolve, reject) => {
        queryDepartTreeList({ userId: this.dataForm.appraiserId }).then((res) => {
          if (!res.success) {
            return this.$message.error(res.message)
          }
          this.departTree = res.result
          resolve()
        })
      })
    },
    loadUserList () {
      return new Promise((resolve, reject) => {
        selectUserList({ deptId: this.dataForm.deptId }).then((res) => {
          if (!res.success) {
            return this.$message.error(res.message)
          }
          this.userList = Object.assign([], res.result)
          console.log('this.userList', this.userList)
          resolve()
        })
      })
    },
    loadUserList2 () {
      return new Promise((resolve, reject) => {
        selectUserList().then((res) => {
          if (!res.success) {
            return this.$message.error(res.message)
          }
          this.userListDefault = Object.assign([], res.result)
          resolve()
        })
      })
    },
    updateOptions(options) {
      this.userList = options
    },
    changeDept (value) {
      if (this.appraiserDept) {
        this.dataForm.deptId = this.appraiserDept.value
        this.dataForm.deptName = this.appraiserDept.label.trim()
      } else {
        this.dataForm.deptId = ''
        this.dataForm.deptName = ''
      }
      console.log('this.dataForm.deptId', this.dataForm.deptId)
      console.log('this.dataForm.deptName', this.dataForm.deptName)
      this.loadUserList()
    },
    changeUser (value) {
      if (this.appraiserUser) {
        this.dataForm.appraiserId = this.appraiserUser.key
        this.dataForm.appraiserName = this.appraiserUser.label.trim()
        let deptId = this.userListDefault.find(res => res.mobile === this.appraiserUser.key).deptId
        if (deptId !== this.appraiserDept.value) {
          this.appraiserDept = {}
          this.dataForm.deptId = ''
          this.dataForm.deptName = ''
        }
      } else {
        this.dataForm.appraiserId = ''
        this.dataForm.appraiserName = ''
      }
      console.log('this.dataForm.appraiserId', this.dataForm.appraiserId)
      console.log('this.dataForm.appraiserName', this.dataForm.appraiserName)
      this.loadDeptTree()
    },
    emptyCurrForm () {
      this.dataForm = Object.assign({}, this.dataFormDefault)
      this.$refs['dataForm'].resetFields()
      this.getInfo()
      console.log('this.dataForm', this.dataForm)
    },
    submitCurrForm () {
      const that = this;
      // 触发表单验证
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          console.log('this.dataForm', this.dataForm)
          that.loading = true;
          let method
          let url
          if (this.title === '编辑关系') {
            method = 'post'
            url = this.url.edit
          } else {
            method = 'post'
            url = this.url.save
          }
          httpAction(url, that.dataForm, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              this.$emit('ok')
              that.onClose();
            } else {
              that.$message.error(res.message);
            }
          }).finally(() => {
            that.loading = false;
          })
        }
      })
    },
    afterVisibleChange () {
    },
    onClose () {
      this.dataForm = this.$options.data().dataForm
      this.appraiserDept = {}
      this.appraiserUser = {}
      this.visible = false
    },
    onCellChange (key, dataIndex, value) {
      const dataSource = [...this.dataForm.subList];
      const target = dataSource.find(item => item.key === key);
      if (target && value) {
        this.assessedUser = value
        target.assessedId = value.key;
        target.assessedName = value.label.trim();
        target.assessedDept = this.userListDefault.find(res => value.key === res.mobile).deptName
        this.dataForm.subList = dataSource;
      }
      console.log('this.assessedUser', this.assessedUser)
    },
    onCellChange2 (key, dataIndex, value) {
      const dataSource = [...this.dataForm.subList];
      const target = dataSource.find(item => item.key === key);
      if (target && value) {
        this.appraiseTies = value
        target.appraiseTiesId = value.key;
        target.appraiseTies = value.label.trim();
        this.dataForm.subList = dataSource;
      }
      console.log('this.appraiseTies', this.appraiseTies)
    },
    onDelete (key) {
      const dataSource = [...this.dataForm.subList];
      this.dataForm.subList = dataSource.filter(item => item.key !== key);
    },
    handleAdd () {
      const newData = {
        key: this.dataForm.subList.length,
        assessedUser: {},
        assessedDept: '',
        appraiseTie: {}
      }
      this.dataForm.subList.push(newData)
    },
  }
}
</script>

<style scoped>

</style>
